package com.xiaojie.service.config;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * ClassNameSentinelApplicationRunner
 *
 * @Description 初始化流控规则 ,当配置到nacos时，不能写该配置
 * @Author yan
 * 2021/5/30 21:36
 * @Version 1.0
 **/
@Slf4j
@Component
public class SentinelApplicationRunner implements ApplicationRunner {
    // 限流规则名称
    private static final String GETORDER_KEY = "orderToMember";
    /**
     * 定义我们的秒杀参数限流的规则
     */
    private static final String GET_SECKULL_RESOURCE_NAME = "GET_SECKULL";
    @Autowired
    private DiscoveryClient discoveryClient;

    @Override
    public void run(ApplicationArguments args) throws Exception {

//        List<FlowRule> rules = new ArrayList<FlowRule>();
//        FlowRule rule1 = new FlowRule();
//        rule1.setResource(GETORDER_KEY);
//        // QPS控制在1
//        rule1.setCount(1);
//        // QPS限流
//        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
//        rule1.setLimitApp("default");
//        rules.add(rule1);
//        // java语言连接nacos读取配置文件  手动加载内存中
//        FlowRuleManager.loadRules(rules);
//        log.info(">>>限流配置加载成功<<<");
        ParamFlowRule rule = new ParamFlowRule(GET_SECKULL_RESOURCE_NAME)
                .setParamIdx(0)
                .setGrade(RuleConstant.FLOW_GRADE_QPS)
                // 相同的参数每秒最多只能访问一次
                .setCount(1);
        ParamFlowRuleManager.loadRules(Collections.singletonList(rule));

    }
}

